import pyautogui
import cv2
import numpy as np
from pynput import keyboard
import time

# 配置参数
IMAGE_PATHS = ['d:\\code\\img\\1.png', 'd:\\code\\img\\2.png', 'd:\\code\\img\\3.png']  # 需要识别的图片列表
HOTKEY = '<alt>+q'  # 快捷键组合
CONFIDENCE = 0.8  # 图像匹配置信度（0-1之间）

def find_image_on_screen(image_path, confidence=0.8):
    """在屏幕上查找目标图片并返回其中心坐标"""
    # 获取屏幕截图
    screenshot = pyautogui.screenshot()
    screenshot = cv2.cvtColor(np.array(screenshot), cv2.COLOR_RGB2BGR)
    
    # 读取目标图片
    target = cv2.imread(image_path)
    if target is None:
        print(f"错误：无法读取目标图片 {image_path}")
        return None
    
    # 模板匹配
    result = cv2.matchTemplate(screenshot, target, cv2.TM_CCOEFF_NORMED)
    min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(result)
    
    # 如果匹配度超过置信度，则返回中心坐标
    if max_val >= confidence:
        h, w = target.shape[:2]
        center_x = max_loc[0] + w // 2
        center_y = max_loc[1] + h // 2
        return (center_x, center_y)
    
    return None

def on_activate():
    """快捷键激活时执行的函数"""
    print(f"检测到快捷键 {HOTKEY} 按下，正在查找图片...")
    
    # 查找并点击图片1
    if len(IMAGE_PATHS) > 0:
        target_position = find_image_on_screen(IMAGE_PATHS[0], CONFIDENCE)
        
        if target_position:
            x, y = target_position
            print(f"找到图片 {IMAGE_PATHS[0]}，位置：({x}, {y})，执行点击...")
            
            # 移动鼠标并点击图片1
            pyautogui.moveTo(x, y, duration=0.2)
            pyautogui.click()
            time.sleep(0.5)
            # 点击指定区域坐标(示例坐标，可根据需要修改)
            pyautogui.click(1500, 592)
            
            # 执行下滑操作
            pyautogui.scroll(-9999)
            pyautogui.scroll(-9999)
            pyautogui.scroll(-9999)
            # 查找并点击图片2
            if len(IMAGE_PATHS) > 1:
                target_position = find_image_on_screen(IMAGE_PATHS[1], CONFIDENCE)
                if target_position:
                    x, y = target_position
                    print(f"找到图片 {IMAGE_PATHS[1]}，位置：({x}, {y})，执行点击...")
                    pyautogui.moveTo(x, y, duration=0.2)
                    pyautogui.click()
                    
                    # 查找并点击图片3
                    if len(IMAGE_PATHS) > 2:
                        target_position = find_image_on_screen(IMAGE_PATHS[2], CONFIDENCE)
                        if target_position:
                            x, y = target_position
                            print(f"找到图片 {IMAGE_PATHS[2]}，位置：({x}, {y})，执行点击...")
                            pyautogui.moveTo(x, y, duration=0.2)
                            pyautogui.click()
                    return
    
    print("未找到任何目标图片")

def main():
    print("程序已启动，等待快捷键触发...")
    print(f"快捷键: {HOTKEY}")
    print(f"目标图片列表: {IMAGE_PATHS}")
    
    # 注册快捷键
    with keyboard.GlobalHotKeys({
        HOTKEY: on_activate
    }) as h:
        h.join()

if __name__ == "__main__":
    main()